package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.utils.common.AppJwtUtil;
import com.heima.common.excpetion.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.wemedia.mapper.WemediaUseMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service("WmUserService")
public class WmUserServiceImpl extends ServiceImpl<WemediaUseMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmUserDTO dto) {

        if (dto == null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword()))
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);

        LambdaQueryWrapper<WmUser> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(WmUser::getName, dto.getName());
        WmUser user = super.getOne(lambdaQuery);

        if (user == null)
            CustException.cust(AppHttpCodeEnum.LOGIN_NOTFOUND_ERROR);

        // 取出数据准备进行比对
        String password = user.getPassword();
        String salt = user.getSalt();
        String passwordResult = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        // 判断密码是否正确
        if (!passwordResult.equals(password)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 修改登录时间
        user.setLoginTime(new Date());
        super.updateById(user);

        // 生成token
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));

        // 将自媒体用户对象封装到Vo对象中
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(user, wmUserVO);

        // 组装数据并返回
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", token);
        hashMap.put("user", wmUserVO);

        return ResponseResult.okResult(hashMap);
    }
}
